package com.zhu.tool_test.spring_cache.aspect;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhu.tool_test.spring_cache.anno.GgCacheEvict;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: tool_test
 * @description: 注解@GgCacheEvictAspect的切面类
 * @author: ggBall
 * @create: 2021-01-03 17:15
 **/
@Component
@Aspect
@Slf4j
public class GgCacheEvictAspect {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    SqlSessionTemplate sqlSessionTemplate;

    @Pointcut("@annotation(com.zhu.tool_test.spring_cache.anno.GgCacheEvict)")
    private void pointCut(){}

    @After("pointCut() && @annotation(ggCacheEvict)")
    private void around(JoinPoint joinPoint, GgCacheEvict ggCacheEvict) throws Throwable {
        // 获取 指定类型
        Class<? extends BaseMapper> aClass = ggCacheEvict.value();
        // 获取 指定key
        String key = ggCacheEvict.key();

        // 移除数据
        Long delete = redisTemplate.opsForHash().delete(key,key);
        if (delete > 0L) {
            log.info("移除成功");
        }
        // 添加数据
        // 从sqlSession 拿对应的mapper
        BaseMapper mapper = sqlSessionTemplate.getMapper(aClass);
        List list = mapper.selectList(null);

        redisTemplate.opsForHash().put(key,key,list);



    }




}
